#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
登录窗口
提供用户登录和注册功能
"""

import tkinter as tk
from tkinter import ttk, messagebox
import re

class LoginWindow:
    """
    登录窗口类
    """
    
    def __init__(self, game_manager, on_login_success=None):
        """
        初始化登录窗口
        
        Args:
            game_manager: 游戏管理器
            on_login_success: 登录成功回调函数
        """
        self.game_manager = game_manager
        self.on_login_success = on_login_success
        
        # 创建窗口
        self.root = tk.Tk()
        self.root.title("VX Battle - 登录")
        self.root.geometry("400x500")
        self.root.resizable(False, False)
        
        # 居中显示
        self.center_window()
        
        # 创建界面
        self.create_widgets()
        
        # 设置焦点
        self.username_entry.focus()
    
    def center_window(self):
        """
        将窗口居中显示
        """
        self.root.update_idletasks()
        width = self.root.winfo_width()
        height = self.root.winfo_height()
        x = (self.root.winfo_screenwidth() // 2) - (width // 2)
        y = (self.root.winfo_screenheight() // 2) - (height // 2)
        self.root.geometry(f"{width}x{height}+{x}+{y}")
    
    def create_widgets(self):
        """
        创建界面组件
        """
        # 主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="VX Battle", font=("Arial", 24, "bold"))
        title_label.pack(pady=(0, 10))
        
        subtitle_label = ttk.Label(main_frame, text="微信小游戏原型", font=("Arial", 12))
        subtitle_label.pack(pady=(0, 30))
        
        # 创建Notebook用于切换登录和注册
        self.notebook = ttk.Notebook(main_frame)
        self.notebook.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        # 登录标签页
        self.login_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.login_frame, text="登录")
        self.create_login_tab()
        
        # 注册标签页
        self.register_frame = ttk.Frame(self.notebook)
        self.notebook.add(self.register_frame, text="注册")
        self.create_register_tab()
        
        # 底部信息
        info_frame = ttk.Frame(main_frame)
        info_frame.pack(fill=tk.X, pady=(10, 0))
        
        info_label = ttk.Label(info_frame, text="首次使用请先注册账号", font=("Arial", 10), foreground="gray")
        info_label.pack()
        
        # 系统信息按钮
        system_info_btn = ttk.Button(info_frame, text="系统信息", command=self.show_system_info)
        system_info_btn.pack(pady=(5, 0))
    
    def create_login_tab(self):
        """
        创建登录标签页
        """
        # 用户名
        ttk.Label(self.login_frame, text="用户名:").pack(anchor=tk.W, pady=(20, 5))
        self.username_entry = ttk.Entry(self.login_frame, font=("Arial", 12))
        self.username_entry.pack(fill=tk.X, pady=(0, 10))
        self.username_entry.bind('<Return>', lambda e: self.password_entry.focus())
        
        # 密码
        ttk.Label(self.login_frame, text="密码:").pack(anchor=tk.W, pady=(0, 5))
        self.password_entry = ttk.Entry(self.login_frame, show="*", font=("Arial", 12))
        self.password_entry.pack(fill=tk.X, pady=(0, 20))
        self.password_entry.bind('<Return>', lambda e: self.login())
        
        # 登录按钮
        login_btn = ttk.Button(self.login_frame, text="登录", command=self.login)
        login_btn.pack(fill=tk.X, pady=(0, 10))
        
        # 记住密码选项
        self.remember_var = tk.BooleanVar()
        remember_cb = ttk.Checkbutton(self.login_frame, text="记住用户名", variable=self.remember_var)
        remember_cb.pack(anchor=tk.W)
        
        # 加载保存的用户名
        self.load_saved_username()
    
    def create_register_tab(self):
        """
        创建注册标签页
        """
        # 用户名
        ttk.Label(self.register_frame, text="用户名:").pack(anchor=tk.W, pady=(20, 5))
        self.reg_username_entry = ttk.Entry(self.register_frame, font=("Arial", 12))
        self.reg_username_entry.pack(fill=tk.X, pady=(0, 5))
        
        username_hint = ttk.Label(self.register_frame, text="3-20个字符，支持字母、数字、下划线", 
                                 font=("Arial", 9), foreground="gray")
        username_hint.pack(anchor=tk.W, pady=(0, 10))
        
        # 密码
        ttk.Label(self.register_frame, text="密码:").pack(anchor=tk.W, pady=(0, 5))
        self.reg_password_entry = ttk.Entry(self.register_frame, show="*", font=("Arial", 12))
        self.reg_password_entry.pack(fill=tk.X, pady=(0, 5))
        
        password_hint = ttk.Label(self.register_frame, text="至少6个字符", 
                                 font=("Arial", 9), foreground="gray")
        password_hint.pack(anchor=tk.W, pady=(0, 10))
        
        # 确认密码
        ttk.Label(self.register_frame, text="确认密码:").pack(anchor=tk.W, pady=(0, 5))
        self.reg_confirm_entry = ttk.Entry(self.register_frame, show="*", font=("Arial", 12))
        self.reg_confirm_entry.pack(fill=tk.X, pady=(0, 10))
        
        # 邮箱（可选）
        ttk.Label(self.register_frame, text="邮箱（可选）:").pack(anchor=tk.W, pady=(0, 5))
        self.reg_email_entry = ttk.Entry(self.register_frame, font=("Arial", 12))
        self.reg_email_entry.pack(fill=tk.X, pady=(0, 20))
        
        # 注册按钮
        register_btn = ttk.Button(self.register_frame, text="注册", command=self.register)
        register_btn.pack(fill=tk.X)
        
        # 绑定回车键
        self.reg_username_entry.bind('<Return>', lambda e: self.reg_password_entry.focus())
        self.reg_password_entry.bind('<Return>', lambda e: self.reg_confirm_entry.focus())
        self.reg_confirm_entry.bind('<Return>', lambda e: self.reg_email_entry.focus())
        self.reg_email_entry.bind('<Return>', lambda e: self.register())
    
    def login(self):
        """
        执行登录
        """
        username = self.username_entry.get().strip()
        password = self.password_entry.get()
        
        # 验证输入
        if not username:
            messagebox.showerror("错误", "请输入用户名")
            self.username_entry.focus()
            return
        
        if not password:
            messagebox.showerror("错误", "请输入密码")
            self.password_entry.focus()
            return
        
        try:
            # 执行登录
            success, message = self.game_manager.login(username, password)
            
            if success:
                # 保存用户名
                if self.remember_var.get():
                    self.save_username(username)
                
                messagebox.showinfo("成功", message)
                
                # 关闭登录窗口
                self.root.destroy()
                
                # 调用成功回调
                if self.on_login_success:
                    self.on_login_success()
            else:
                messagebox.showerror("登录失败", message)
                self.password_entry.delete(0, tk.END)
                self.password_entry.focus()
                
        except Exception as e:
            messagebox.showerror("错误", f"登录时发生错误: {str(e)}")
    
    def register(self):
        """
        执行注册
        """
        username = self.reg_username_entry.get().strip()
        password = self.reg_password_entry.get()
        confirm_password = self.reg_confirm_entry.get()
        email = self.reg_email_entry.get().strip()
        
        # 验证输入
        if not self.validate_register_input(username, password, confirm_password, email):
            return
        
        try:
            # 执行注册
            success, message = self.game_manager.register(username, password, email)
            
            if success:
                messagebox.showinfo("成功", message)
                
                # 清空注册表单
                self.reg_username_entry.delete(0, tk.END)
                self.reg_password_entry.delete(0, tk.END)
                self.reg_confirm_entry.delete(0, tk.END)
                self.reg_email_entry.delete(0, tk.END)
                
                # 切换到登录标签页并填入用户名
                self.notebook.select(0)
                self.username_entry.delete(0, tk.END)
                self.username_entry.insert(0, username)
                self.password_entry.focus()
            else:
                messagebox.showerror("注册失败", message)
                
        except Exception as e:
            messagebox.showerror("错误", f"注册时发生错误: {str(e)}")
    
    def validate_register_input(self, username, password, confirm_password, email):
        """
        验证注册输入
        
        Args:
            username: 用户名
            password: 密码
            confirm_password: 确认密码
            email: 邮箱
            
        Returns:
            验证是否通过
        """
        # 验证用户名
        if not username:
            messagebox.showerror("错误", "请输入用户名")
            self.reg_username_entry.focus()
            return False
        
        if len(username) < 3 or len(username) > 20:
            messagebox.showerror("错误", "用户名长度必须在3-20个字符之间")
            self.reg_username_entry.focus()
            return False
        
        if not re.match(r'^[a-zA-Z0-9_]+$', username):
            messagebox.showerror("错误", "用户名只能包含字母、数字和下划线")
            self.reg_username_entry.focus()
            return False
        
        # 验证密码
        if not password:
            messagebox.showerror("错误", "请输入密码")
            self.reg_password_entry.focus()
            return False
        
        if len(password) < 6:
            messagebox.showerror("错误", "密码长度至少6个字符")
            self.reg_password_entry.focus()
            return False
        
        # 验证确认密码
        if password != confirm_password:
            messagebox.showerror("错误", "两次输入的密码不一致")
            self.reg_confirm_entry.focus()
            return False
        
        # 验证邮箱（如果提供）
        if email and not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
            messagebox.showerror("错误", "邮箱格式不正确")
            self.reg_email_entry.focus()
            return False
        
        return True
    
    def save_username(self, username):
        """
        保存用户名到本地文件
        
        Args:
            username: 用户名
        """
        try:
            import os
            config_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data')
            os.makedirs(config_dir, exist_ok=True)
            
            config_file = os.path.join(config_dir, 'login_config.txt')
            with open(config_file, 'w', encoding='utf-8') as f:
                f.write(username)
        except Exception:
            pass  # 忽略保存失败
    
    def load_saved_username(self):
        """
        加载保存的用户名
        """
        try:
            import os
            config_file = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'data', 'login_config.txt')
            
            if os.path.exists(config_file):
                with open(config_file, 'r', encoding='utf-8') as f:
                    username = f.read().strip()
                    if username:
                        self.username_entry.insert(0, username)
                        self.remember_var.set(True)
                        self.password_entry.focus()
        except Exception:
            pass  # 忽略加载失败
    
    def show_system_info(self):
        """
        显示系统信息
        """
        try:
            system_info = self.game_manager.get_system_info()
            
            info_text = "系统信息\n\n"
            info_text += f"数据库连接: {'正常' if system_info.get('database_connected', False) else '失败'}\n"
            info_text += f"最大挂机时长: {system_info.get('max_idle_hours', 0)} 小时\n"
            info_text += f"版本: {system_info.get('version', '未知')}\n\n"
            
            features = system_info.get('features', [])
            if features:
                info_text += "功能特性:\n"
                for feature in features:
                    info_text += f"• {feature}\n"
            
            if 'error' in system_info:
                info_text += f"\n错误: {system_info['error']}"
            
            messagebox.showinfo("系统信息", info_text)
            
        except Exception as e:
            messagebox.showerror("错误", f"获取系统信息失败: {str(e)}")
    
    def run(self):
        """
        运行登录窗口
        """
        self.root.mainloop()
    
    def destroy(self):
        """
        销毁窗口
        """
        self.root.destroy()